/**
 * @FileName: LoginController.java
 * @Author
 * @Description:
 * @Date 2016年1月4日 上午11:39:53
 * @CopyRight ZTE Corporation
 */
package cn.hpclub.server.controller.client;

import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.jfinal.aop.Before;
import com.jfinal.core.Controller;
import com.jfinal.ext.interceptor.POST;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Model;
import com.jfinal.plugin.activerecord.Record;

import cn.hpclub.server.constant.ClientApiConstant;
import cn.hpclub.server.model.MemberOrg;
import cn.hpclub.server.model.Organization;
import cn.hpclub.server.restful.API;
import cn.hpclub.server.util.InterfaceUtil;

@Before(value = { POST.class })
@API("/StoreServer/StoreMasterInfo")
public class StoreMasterInfoController<M extends Model<M>> extends Controller{
    private static Logger log = LoggerFactory.getLogger(StoreMasterInfoController.class);

    public void GainEmpCode(){
        String appkey = getPara(ClientApiConstant.Key.APPKEY);
        String timestamp = getPara(ClientApiConstant.Key.TIMESTAMP);
        String userId = getPara(ClientApiConstant.Key.USER_ID);

        // log.info("GainEmpCode: appkey=" + appkey + ",userId=" + userId +
        // ",timestamp=" + timestamp);
        JSONObject jo = null;
        try{
            jo = getEmpCodeResponse(userId, appkey);
        }
        catch(Exception e){
            jo = processException(e);
        }
        renderText(jo.toString());
    }

    private JSONObject processException(Exception e){
        // log.info("processException:" + e.getMessage());

        int resultCode = ClientApiConstant.ResultCode.FAILED;
        String message = ClientApiConstant.Msg.MSG_EXCEPTION;

        if(e instanceof UserNotExistException){
            resultCode = ClientApiConstant.ResultCode.NOT_EXIST;
            message = ClientApiConstant.Msg.ACCOUNT_NOT_EXIST;
        } else if(e instanceof IllegalParameterException || e instanceof NumberFormatException){
            resultCode = ClientApiConstant.ResultCode.PARAM_ERROR;
            message = ClientApiConstant.Msg.PARA_ILLEGAL;
        } else if(e instanceof EmpCodeIsEmptyException){
            resultCode = ClientApiConstant.ResultCode.FAILED;
            message = ClientApiConstant.Msg.EMP_CODE_ERROR;
        } else{
            e.printStackTrace();
        }
        return getResponseObj(resultCode, message, ClientApiConstant.Msg.EMPTY);
    }

    /**
     * @Title: getResponseData
     * @Description:TODO
     * @param userId
     *            void
     * @param appkey
     *            TODO
     * @throws IllegalParameterException
     * @throws EmpCodeIsEmptyException
     */
    private JSONObject getEmpCodeResponse(String userId, String appkey)
            throws UserNotExistException, IllegalParameterException, EmpCodeIsEmptyException{
        if(!ClientApiConstant.APPKEY_DZG_STRING.equals(appkey) || StrKit.isBlank(userId)){
            throw new IllegalParameterException("parameter is error.appkey=" + appkey + ",userId=" + userId);
        }

        MemberOrg member = MemberOrg.dao.getMemberOrgById(Long.parseLong(userId));
        if(member == null){
            throw new UserNotExistException("error: userid " + userId + " is not exist.");
        }

        int orgId = member.getInt(MemberOrg.ORG_ID);
        String channelCode = Organization.dao.getNumCodeById(orgId);
        String empCode = member.getStr(MemberOrg.EMP_CODE);
        if(StrKit.isBlank(empCode)){
            throw new EmpCodeIsEmptyException("error: EmpCode is empty.");
        }
        String mobile = member.getStr(MemberOrg.MOBILE);
        String cityChannelID = getCityChannelID(orgId);

        // log.info("userId=" + userId + ",channelCode=" + channelCode +
        // ",empCode=" + empCode + ",mobile=" + mobile
        // + ",cityChannelID=" + cityChannelID);
        return createResponse(channelCode, empCode, mobile, cityChannelID);
    }

    /**
     * @Title: createResponse
     * @Description:TODO
     * @param channelCode
     * @param empCode
     * @param mobile
     * @param cityChannelID
     * @return JSONObject
     */

    private JSONObject createResponse(String channelCode, String empCode, String mobile, String cityChannelID){
        JSONObject data = new JSONObject();
        data.put("PhoneNo", mobile).put("CityChannelId", cityChannelID);
        data.put("ChannelId", channelCode).put("EmpCode", empCode == null ? "" : empCode);

        JSONObject jo = getResponseObj(ClientApiConstant.ResultCode.SUCCESS_CODE, ClientApiConstant.Msg.SUCCESS, data);
        return jo;
    }

    private String getCityChannelID(int orgID){
        String numCode = "";
        String sql = InterfaceUtil.getCitySql(String.valueOf(orgID), "id, NumCode");
        Record record = Db.findFirst(sql);
        if(record != null){
            numCode = record.getStr("NumCode");
        }
        return numCode;
    }

    private JSONObject getResponseObj(int code, String msg, Object data){
        JSONObject rjson = new JSONObject();
        rjson.put(ClientApiConstant.Key.RESULT_CODE, code);
        rjson.put(ClientApiConstant.Key.MESSAGE, msg);
        rjson.put(ClientApiConstant.Key.DATA, data);
        return rjson;
    }

    private static class IllegalParameterException extends Exception{
        private static final long serialVersionUID = 2711822818163282004L;

        public IllegalParameterException(String message){
            super(message);
        }
    }

    private static class UserNotExistException extends Exception{
        private static final long serialVersionUID = -9167617956947822005L;

        public UserNotExistException(String message){
            super(message);
        }
    }

    private static class EmpCodeIsEmptyException extends Exception{
        private static final long serialVersionUID = -3808731266869532483L;

        public EmpCodeIsEmptyException(String message){
            super(message);
        }
    }
}
